import { Console } from 'console';
import { HID } from './download.js';
import fs from 'fs';
import path from 'path';
const png404 = path.resolve('./plugins/qiqi-plugin/resources/BH3/404.png');
const png405 = path.resolve('./plugins/qiqi-plugin/resources/BH3/405.png');
const levelbf = {
  1: "初级区",
  2: "中级区",
  3: "高级区",
  4: "终极区",
};
async function PAbyssR(abyssR) {
  try {
    if (!abyssR || typeof abyssR !== 'object') {
      throw new Error("传入的数据无效或为空");
    }
    const { score, updated_time_second, rank, settled_cup_number, cup_number, level, settled_level, boss, lineup} = abyssR;
    let {elf}=abyssR
    if (!boss) {
      throw new Error("数据缺少必要的字段boss");
    }
    const bossPath = await HID(boss.id, boss.avatar, './plugins/qiqi-plugin/resources/BH3/BOSS');
    const bossava111 = path.resolve(bossPath);
    let elfResolvedPath;
    if (!elf || !elf.id || !elf.avatar) {
        elfResolvedPath = png404; 
        elf = {
             id: '未知',
             name: '无',
             avatar: elfResolvedPath
       };
    } else {
           const elfPath = await HID(elf.id, elf.avatar, './plugins/qiqi-plugin/resources/BH3/EF');
           elfResolvedPath = path.resolve(elfPath) || png404;
    }
    const processedLineup = await Promise.all(abyssR.lineup.map(async char => {
      if (!char || !char.id || !char.icon_path) {
        return {
          icon_path: png404,
          star: png404 
        };
      }
      const charPath = await HID(char.id, char.icon_path, './plugins/qiqi-plugin/resources/BH3/AvatarIcon');
      const iconFileName = `${char.id}.png`;
      const resolvedIconPath = path.resolve(`./plugins/qiqi-plugin/resources/BH3/AvatarIcon/${iconFileName}`)|| png404;
      let starIconPath;
      if (char.star === 3) {
        starIconPath = path.resolve('./plugins/qiqi-plugin/resources/BH3/SSS/s.png')|| png404;
      } else if (char.star === 4) {
        starIconPath = path.resolve('./plugins/qiqi-plugin/resources/BH3/SSS/ss.png')|| png404;
      } else if (char.star === 5) {
        starIconPath = path.resolve('./plugins/qiqi-plugin/resources/BH3/SSS/sss.png')|| png404;
      } else if (char.star === 2) { 
        starIconPath = path.resolve('./plugins/qiqi-plugin/resources/BH3/SSS/a.png')|| png404;
      } else if (char.star === 1) { 
        starIconPath = path.resolve('./plugins/qiqi-plugin/resources/BH3/SSS/b.png')|| png404;
      }
      while (resolvedIconPath.length < 3) {
        resolvedIconPath.push({
          icon_path: png404,
          star: png404
        });
      }
      return {
        icon_path: resolvedIconPath || png404,
        star: starIconPath || png404,
      };
    }));
    const result = {
      score,
      updated_time_second,
      boss: {
        ...boss,
        local_avatar_path: bossava111  
      },
      lineup: processedLineup, 
      rank,
      settled_cup_number,
      cup_number,
      level,
      settled_level,
      elf: {
        ...elf,
        local_avatar_path: elfResolvedPath 
      }
    };
    // console.log(result)
    return result;
  } catch (error) {
    console.error("PAbyssR 处理出错:", error.message);
    return {
      error: true,
      message: error.message,
      id123:'none'
    };
  }
}
async function bfbh(bfbh3) {
  try {
    if (!bfbh3 || typeof bfbh3 !== 'object') {
      throw new Error("传入的数据无效或为空");
    }
    const { score, rank, ranking_percentage, area, time_second, battle_infos } = bfbh3;
    if (!score || !ranking_percentage || !battle_infos) {
      throw new Error("数据缺少必要的字段");
    }
    const bftime = uptime(time_second) || "未知时间";
    const bflel = levelbf[Number(area)] || "未知区域";
    let elfResolvedPath;
    const results = []; 
    for (const battle of battle_infos) {
      const bossPath = await HID(battle.boss.id, battle.boss.avatar, './plugins/qiqi-plugin/resources/BH3/BOSS');
      const bossAvatarPath = path.resolve(bossPath);
      let elf = battle.elf;
      if (!elf || !elf.id || !elf.avatar) {
          elfResolvedPath = png404; 
          elf = {
               id: '未知',
               name: '无',
               avatar: elfResolvedPath
         };
      } else {
             const elfPath = await HID(elf.id, elf.avatar, './plugins/qiqi-plugin/resources/BH3/EF');
             elfResolvedPath = path.resolve(elfPath) || png404;
      }
      const processedLineup = await Promise.all(battle.lineup.map(async char => {
        if (!char || !char.id || !char.icon_path) {
          return {
            icon_path: png404,
            star: png404 
          };
        }
      const charPath = await HID(char.id, char.icon_path, './plugins/qiqi-plugin/resources/BH3/AvatarIcon');
      const iconFileName = `${char.id}.png`;
      const resolvedIconPath = path.resolve(`./plugins/qiqi-plugin/resources/BH3/AvatarIcon/${iconFileName}`)|| png404;
      let starIconPath;
        if (char.star === 3) {
          starIconPath = path.resolve('./plugins/qiqi-plugin/resources/BH3/SSS/s.png')|| png404;
        } else if (char.star === 4) {
          starIconPath = path.resolve('./plugins/qiqi-plugin/resources/BH3/SSS/ss.png')|| png404;
        } else if (char.star === 5) {
          starIconPath = path.resolve('./plugins/qiqi-plugin/resources/BH3/SSS/sss.png')|| png404;
        } else if (char.star === 2) { 
          starIconPath = path.resolve('./plugins/qiqi-plugin/resources/BH3/SSS/a.png')|| png404;
        } else if (char.star === 1) { 
          starIconPath = path.resolve('./plugins/qiqi-plugin/resources/BH3/SSS/b.png')|| png404;
        }
        return {
          icon_path: resolvedIconPath|| png404,
          star: starIconPath
        };
      }));
      while (processedLineup.length < 3) {
        processedLineup.push({
          icon_path: png404,
          star: png404
        });
      }
      const result = {
        elf: {
          id: battle.elf.id,
          name: battle.elf.name,
          avatar: elfResolvedPath
        },
        lineup: processedLineup,
        boss: {
          id: battle.boss.id,
          name: battle.boss.name,
          avatar: bossAvatarPath
        },
        score: battle.score
      };

      results.push(result);
    }
    while (results.length < 3) {
      results.push({
        elf: {
          id: '未知',
          name: '无',
          avatar: png404
        },
        lineup: Array(3).fill({ icon_path: png404, star: png404 }),
        boss: {
          id: '未知',
          name: '无',
          avatar: png405
        },
        score: 0
      });
    }
    // console.log(results)
    return {
      bfrk: rank,
      bfae:bflel,
      bfuptime:bftime,
      bfekpc:  ranking_percentage,
      tlscore: score, 
      bf: results
    };
  } catch (error) {
    return {
      error: true,
      message: error.message,
    };
  }
}

async function PGW(godwar) {
  try {
    // console.log('这是测试123')
    if (!godwar || typeof godwar !== 'object') {
      throw new Error("传入的数据无效或为空");
    }

    const { score, settle_time_second,cost_time } = godwar||{};
    if (!score || !settle_time_second) {
      throw new Error("数据缺少必要的字段");
    }
    // const result = []; 
    const gwstarttime = cstime(cost_time) || "未知时间";
    const gwsts = uptime(settle_time_second)|| "未知时间";
    let elf = godwar.elf;
    let exitem = godwar.extra_item_icon||{};
    let assextraitem = godwar.assistant_extra_item||{};
    let gwa;
    let gwastar;
    let ex1;
    let ex2;
    if(!exitem){
       ex1 = {
        extra_item_icon:png404
       }
    }else{
      const urlid = (exitem.match(/\/(\d+)\.png$/) || [])[1];
      const exPath = await HID(urlid, exitem, './plugins/qiqi-plugin/resources/BH3/extraicon');
      ex1 = path.resolve(exPath) || png404;
    }
    if(!assextraitem){
      ex2 = {
        assistant_extra_item:png404
      }
   }else{
     const urlid1 = (assextraitem.match(/\/(\d+)\.png$/) || [])[1];
     const exPath = await HID(urlid1, assextraitem, './plugins/qiqi-plugin/resources/BH3/extraicon');
     ex2 = path.resolve(exPath) || png404;
   }
    let elfResolvedPath;
    if (!elf || !elf.id || !elf.avatar) {
        elfResolvedPath = png404; 
        elf = {
             id: '未知',
             name: '无',
             avatar: elfResolvedPath
       };
    } else {
           const elfPath = await HID(elf.id, elf.avatar, './plugins/qiqi-plugin/resources/BH3/EF');
           elfResolvedPath = path.resolve(elfPath) || png404;
    }
    let maingwa = godwar.main_avatar|| [];
    if (!maingwa){
         gwa = {
          icon_path:png404,
          star:png404
         };
    } else {
      const gwPath = await HID(maingwa.id, maingwa.icon_path, './plugins/qiqi-plugin/resources/BH3/AvatarIcon');
      
      let starIconPath;
      if (maingwa.star === 3) {
        starIconPath = path.resolve('./plugins/qiqi-plugin/resources/BH3/SSS/s.png')|| png404;
      } else if (maingwa.star === 4) {
        starIconPath = path.resolve('./plugins/qiqi-plugin/resources/BH3/SSS/ss.png')|| png404;
      } else if (maingwa.star === 5) {
        starIconPath = path.resolve('./plugins/qiqi-plugin/resources/BH3/SSS/sss.png')|| png404;
      } else if (maingwa.star === 2) { 
        starIconPath = path.resolve('./plugins/qiqi-plugin/resources/BH3/SSS/a.png')|| png404;
      } else if (maingwa.star === 1) { 
        starIconPath = path.resolve('./plugins/qiqi-plugin/resources/BH3/SSS/b.png')|| png404;
      }
      gwa = {
        star: starIconPath,
        icon_path: path.resolve(gwPath) || png404,
      }
    }
    let supava = godwar.support_avatars|| [];
    const supportava = await Promise.all(supava.map(async char => {
      if (!char || !char.id || !char.icon_path) {
        return {
          icon_path: png404,
        };
      }
      const charPath = await HID(char.id, char.icon_path, './plugins/qiqi-plugin/resources/BH3/AvatarIcon');
      const iconFileName = `${char.id}.png`;
      const resolvedIconPath = path.resolve(`./plugins/qiqi-plugin/resources/BH3/AvatarIcon/${iconFileName}`)|| png404;
      return{
        icon_path: resolvedIconPath|| png404,
      };
    }));
    while (supportava.length <2 ){ 
      supportava.push({
        icon_path: png404,
      });
    }
    const result = {
      score:score,
      settle_time_second:gwsts,
      cost_time:gwstarttime,
      support_avatars:ex1,
      assistant_extra_ite:ex2,
      mainavatar:gwa,
      supportavatars:supportava,
      elf: {
        id: godwar.elf.id,
        name: godwar.elf.name,
        avatar: elfResolvedPath
      },
    };
    // console.log(result)
    return(result)
  } catch (error) {
    return {
      error: true,
      message: error.message,
    };
  }
}

async function BVK(data) {
  try {
    if (!data || !data.data || !Array.isArray(data.data.characters)) {
      throw new Error('无效的数据结构');
    }

    const characters = data.data.characters;

    return await Promise.all(characters.map(async (char) => {
      if (!char || !char.character) {
        console.warn('发现无效的角色数据，跳过处理');
        return null;
      }
      const { character } = char;
      const avatarPath = await HID(character.avatar.id, character.avatar.icon_path, './plugins/qiqi-plugin/resources/BH3/AvatarIcon');
      const avatarIconPath = path.resolve(avatarPath) || png404;
       let avatarStarPath;
       if (character.avatar.star === 3) {
         avatarStarPath = path.resolve('./plugins/qiqi-plugin/resources/BH3/SSS/s.png') || png404;
       } else if (character.avatar.star === 4) {
         avatarStarPath = path.resolve('./plugins/qiqi-plugin/resources/BH3/SSS/ss.png') || png404;
       } else if (character.avatar.star === 5) {
         avatarStarPath = path.resolve('./plugins/qiqi-plugin/resources/BH3/SSS/sss.png') || png404;
       } else if (character.avatar.star === 2) {
         avatarStarPath = path.resolve('./plugins/qiqi-plugin/resources/BH3/SSS/a.png') || png404;
       } else if (character.avatar.star === 1) {
         avatarStarPath = path.resolve('./plugins/qiqi-plugin/resources/BH3/SSS/b.png') || png404;
       } else {
         avatarStarPath = png404;
       }
      let weaponIconPath = png404;
      let weaponStar = png404;
      if (character.weapon && character.weapon.id !== 0) {
        const weaponPath = await HID(character.weapon.id, character.weapon.icon, './plugins/qiqi-plugin/resources/BH3/WeaponIcon');
        weaponIconPath = path.resolve(weaponPath) || png404;
        const starFileName = `${character.weapon.rarity}_of_${character.weapon.max_rarity}.png`;
        weaponStar = path.resolve(`./plugins/qiqi-plugin/resources/BH3/SSS/${starFileName}`);
      }
      const stigmatas = await Promise.all((character.stigmatas || []).map(async (stigmata, index) => {
        if (stigmata.id === 0) {
          return {
            id: 0,
            name: "",
            level: 0,
            icon: png404,
            star: png404
          };
        }
        const stigmataPath = await HID(stigmata.id, stigmata.icon, './plugins/qiqi-plugin/resources/BH3/StigmataIcon');
        const starFileName = `${stigmata.rarity}_of_${stigmata.max_rarity}.png`;
        const starPath = path.resolve(`./plugins/qiqi-plugin/resources/BH3/SSS/${starFileName}`);
        return {
          id: stigmata.id,
          name: stigmata.name,
          level: stigmata.level,
          icon: path.resolve(stigmataPath) || png404,
          star: starPath
        };
      }));
      while (stigmatas.length < 3) {
        stigmatas.push({
          id: 0,
          name: "",
          level: 0,
          icon: png404,
          star: png404
        });
      }

      return {
        avatar: {
          id: character.avatar.id,
          name: character.avatar.name,
          star: avatarStarPath,
          icon_path: avatarIconPath,
          level: character.avatar.level,
          attribute_id: character.avatar.attribute_id,
          attribute_background_path: character.avatar.attribute_background_path
        },
        weapon: {
          id: character.weapon ? character.weapon.id : 0,
          name: character.weapon ? character.weapon.name : "",
          level: character.weapon ? character.weapon.level : 0,
          icon: weaponIconPath,
          star: weaponStar
        },
        stigmatas: stigmatas
      };
    }));
  } catch (error) {
    console.error("处理角色数据出错:", error.message);
    return { error: true, message: error.message };
  }
}

function uptime(customTimestamp) {
  const referenceTimestamp = 1726588800;
  const referenceDate = new Date('2024-09-18T00:00:00Z');
  const timeDifference = (customTimestamp - referenceTimestamp) * 1000;
  const targetDate = new Date(referenceDate.getTime() + timeDifference);
  const year = targetDate.getFullYear();
  const month = targetDate.getMonth() + 1; 
  const day = targetDate.getDate();
      return `${year}/${month}/${day}`; 
}
function cstime(seconds) {
  const minutes = Math.floor(seconds / 60);
  const remainingSeconds = seconds % 60;
  return `${minutes}分${remainingSeconds}秒`;
}
export { PAbyssR, uptime,bfbh,cstime,PGW,BVK};
